<template>
	<view v-if="orderInfo">
		<!--  && orderStatus>=0 -->
		<!-- 问诊订单状态 -->
		<view class="top-warp">
			<!-- 待接诊 -->
			<block v-if="orderStatus==0">
				<view class="top bg-green">
					<text></text>
					<block v-if="isDoc==0">已通知医生尽快接诊，{{no_patient_time_show}}内医生未回复将自动退诊</block>
					<block v-else>{{no_patient_time_show}}内医生未回复将自动退诊</block>
				</view>
			</block>
			<!-- 接诊中 -->
			<block v-if="orderStatus==1">
				<view class="top bg-red"><text></text>正在咨询中，此咨询将在 {{downTimeTxt}} 后结束</view>
			</block>
			<!-- 结束咨询 -->
			<block v-if="orderStatus==2">
				<view class="top bg-green">
					<text></text>
					<block v-if="isDoc==0">本次咨询已结束，您可咨询其他医生</block>
					<block v-else>本次咨询已结束</block>
				</view>
			</block>
			<!-- 拒绝接诊 -->
			<block v-if="orderStatus==-1">
				<view class="top bg-red">
					<text></text>
					<block v-if="isDoc==0">本次咨询已退诊，您可咨询其他医生</block>
					<block v-else>本次咨询已退诊</block>
				</view>
			</block>
			<!-- 用户主动取消 -->
			<block v-if="orderStatus==-2">
				<view class="top bg-red">
					<text></text>
					<block v-if="isDoc==0">本次咨询已退诊，您可咨询其他医生</block>
					<block v-else>本次咨询已退诊</block>
				</view>
			</block>
			<!-- 拒绝接诊 -->
			<block v-if="orderStatus==-3">
				<view class="top bg-red">
					<text></text>
					<block v-if="isDoc==0">本次咨询已退诊，您可咨询其他医生</block>
					<block v-else>本次咨询已退诊</block>
				</view>
			</block>
			<!-- 待支付 -->
			<block v-if="orderStatus==-4">
				<view class="top bg-red">
					<text></text>
					<block v-if="isDoc==0">
						请在{{formatSeconds(orderInfo.consultation_no_pay_time_config,{h:'小时',i:'分钟',s:'秒'})}}内完成支付，超时订单将取消
					</block>
					<block v-else>待支付</block>
				</view>
			</block>

			<!-- 病人详情 -->
			<view class="jzr_info" v-if="isDoc==1 && orderInfo.user_the_patient_info" @click="toHz">
				{{orderInfo.user_the_patient_info.name}}<text>{{orderInfo.user_the_patient_info.sex==1?'男':'女'}}</text>{{orderInfo.user_the_patient_info.age}}岁
				<view>查看病人详情 > </view>
			</view>
		</view>

		<!-- 聊天窗口 -->
		<view class="content">
			<scroll-view class="list-warp" scroll-y="true" upper-threshold="50"
				:style="'top:'+contentTop+'rpx;bottom:'+contentBottom+'rpx;'+(orderStatus==2&&(isDoc!=1||orderInfo.has_user_the_patient==1)?'padding-bottom: 120rpx':'')"
				:scroll-with-animation="scrollAnimation" :scroll-top="scrollTop" :scroll-into-view="scrollToView"
				@scrolltoupper="loadHistory" @touchstart="onTextareaFocus">

				<!-- 加载历史数据waitingUI -->
				<block v-if="isHistoryLoading == true">
					<view class="loading">
						<view class="spinner">
							<view class="rect1"></view>
							<view class="rect2"></view>
							<view class="rect3"></view>
							<view class="rect4"></view>
							<view class="rect5"></view>
						</view>
					</view>
				</block>

				<view class="item" v-for="(item,index) in chatList" :key="index" :id="'chat-'+index">
					<!-- 系统消息 时间/提示 -->
					<view class="system-chat" v-if="item.fromType=='system'">
						<!-- 待接诊 -->
						<view class="waiting-for-treatment" v-if="item.type=='waiting-for-treatment' && orderStatus==0">
							待接诊，{{downTimeTxt}}后未接诊将自动退诊</view>
						<!-- 提示 -->
						<view class="tip" v-if="item.type=='tip'">{{item.content.text}}</view>
						<!-- 时间 -->
						<view class="time" v-if="item.type=='time'">{{item.content.text}}</view>
					</view>
					<!-- 用户消息 -->
					<view
						:class="'user-chat '+(((isDoc==1?item.from.prefix=='DT':item.from.prefix=='HZ')&&item.from.uid==FromUser.uid)?'my':'other')"
						v-if="item.fromType=='user'">
						<!-- 左-头像 -->
						<!--  -->
						<view class="avatar">
							<image :src="ToUser.avatar"
								v-if="!((isDoc==1?item.from.prefix=='DT':item.from.prefix=='HZ')&&item.from.uid==FromUser.uid)">
							</image>
						</view>

						<view class="content-outer">
							<view class="content-inner">
								<!-- 文字卡片 -->
								<view class="textCard" v-if="item.type=='textCard'">
									<view class="row" v-for="(n,v) in item.content.list" :key="v">
										<view style="white-space:nowrap;margin-right: 16rpx;" class="left">{{n.name}}:</view>
										<view class="right">{{n.value}}</view>
									</view>
								</view>
								<!-- 多图 -->
								<view class="imgs" v-if="item.type=='imgs'">
									<image :src="n.url" :style="'width:'+n.w+'rpx'" mode="widthFix"
										v-for="(n,v) in item.content.list" :key="v" @click="showPic(n)"></image>
								</view>
								<!-- 单图 -->
								<view class="img" v-if="item.type=='img'">
									<image :src="item.content.url" :style="'width:'+item.content.w+'rpx'"
										mode="widthFix" @click="showPic(item.content)"></image>
								</view>
								<!-- 文字图片 -->
								<view class="text" v-if="item.type=='text'">
									<rich-text :nodes="item.content.text"></rich-text>
								</view>
								<!-- 语音消息 -->
								<view class="voice" v-if="item.type=='voice'" @click="playVoice(item,index)"
									:class="playMsgid == index?'play':''">
									<view class="length">{{item.content.length}}</view>
									<view class="icon my-voice"></view>
								</view>
								<!-- 文件 -->
								<view class="file" v-if="item.type=='file'">
									<view class="con u-flex u-flex-y-center" @click="openFile(item.content)">
										<view>
											<view class="tit">{{item.content.name}}</view>
											<view class="ftime">{{item.content.time}}</view>
										</view>
										<image :src="'/static/lj/common/file'+item.content.type+'.png'" mode=aspectFill>
										</image>
									</view>
									<view class="foot u-flex u-flex-y-center">
										<image src="/static/lj/common/filelogo.png" mode="aspectFill"></image>
										<view>维普医疗</view>
									</view>
								</view>
								<!-- 电子处方 -->
								<view class="dzcf" v-if="item.type=='dzcf'"
									@click="toDrug(item.log_id,item.content.cf_id)">
									<view class="title">
										<image
											:src="'/static/cf-icon'+(((isDoc==1?item.from.prefix=='DT':item.from.prefix=='HZ')&&item.from.uid==FromUser.uid)?'-w':'')+'.png'"
											mode="aspectFill">
											<text>电子处方</text>
									</view>
									<view class="textCard">
										<view class="row" v-for="(n,v) in item.content.list" :key="v">
											<view class="left">{{n.name}}</view>
											<view class="right">{{n.value}}</view>
										</view>
									</view>
									<view class="bottom" v-if="isDoc!=1">
										<navigator :url="'/pagesA/drug/info?id='+item.content.cf_id">领取药方</navigator>
									</view>
								</view>
								<!-- 视频聊天 -->
								<view class="video_bos" v-if="item.type=='video'">
									<view class="flex-row-start title">
										<uni-icons class="uni_icons" style="margin-right: 10rpx;" type="phone"
											size="18"></uni-icons>
										<text>视频问诊</text>
									</view>
									<view>正在邀请您进行视频问诊，点击按钮加入</view>
									<view class="bottom">
										<navigator
											:url="'/pagesA/common/video?id=' + orderInfo.id + '&type='+(isDoc==1?'doc':'user')">
											加入</navigator>
									</view>
								</view>
							</view>
						</view>

						<!-- 右-头像 -->
						<!--  -->
						<view class="avatar">
							<image :src="FromUser.avatar"
								v-if="((isDoc==1?item.from.prefix=='DT':item.from.prefix=='HZ')&&item.from.uid==FromUser.uid)">
							</image>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>

		<view class="foot-btns" v-if="orderStatus==0">
			<!-- 取消咨询 -->
			<block v-if="isDoc==0">
				<view class="btn btn-turquoise" @click="refundOrder" style="width:470rpx;margin-bottom:30rpx;">取消</view>
			</block>
			<!-- 拒诊/接诊 -->
			<block v-else>
				<view class="btn btn-turquoise" @click="receivePatient" style="margin-bottom:70rpx;">接诊</view>
				<view class="btn btn-turquoise" @click="refusePatient" style="margin-bottom:70rpx;">拒绝接诊</view>
			</block>
		</view>
		<view class="foot-btns" v-if="orderStatus==2">
			<block v-if="isDoc==1">
				<!-- <view class="btn btn-turquoise" @click="chufang" style="width:470rpx;">开处方</view> -->
			</block>
			<block v-else>
				<view class="comment-tip" v-if="(orderStatus==2&&orderInfo.status!='comment') && showCommentTip">
					<view class="txt">问诊已结束，对服务满意请给医生五星好评哦~</view>
					<view>
						<view class="icon">
							<image src="/static/guanbi.png" mode="aspectFill" @click="showCommentTip=false"></image>
						</view>
						<view class="btn" @click="toPj">写评论</view>
					</view>
				</view>
				<view class="btn btn-turquoise" @click="restoration" style="width:470rpx;">再次复诊</view>
			</block>
		</view>

		<!-- 底部输入栏 -->
		<view class="foot-panel" v-if="orderStatus==1 || (isDoc==1&&orderStatus==2&&orderInfo.has_user_the_patient==1)">
			<!-- 操作栏 -->
			<view class="oper-panel" v-if="isDoc==1&&orderStatus==1">
				<view class="btn" @click="endPatient">完成接诊</view>
			</view>

			<!-- 输入栏 -->
			<view class="input-panel">
				<view class="icon-mode">
					<!-- H5下不能录音，输入栏布局改动一下 -->
					<!-- #ifdef H5 -->
					<view class="icon jianpan" @click="onTextareaFocus"></view>
					<!-- #endif -->
					<!-- #ifndef H5 -->
					<view class="icon yuyin" @click="openVoice" v-if="!showVoice"></view>
					<view class="icon jianpan" @click="onTextareaFocus" v-else></view>
					<!-- #endif -->
				</view>

				<view class="textbox" v-show="!showVoice">
					<view class="text-mode u-flex u-flex-y-center">
						<textarea cursor-spacing="40" @linechange="autoHeight" @focus="onTextareaFocus"
							:auto-height="textareaAutoHeight" v-model="textMsg" placeholder="输入..." />
					</view>
				</view>
				<view class="textbox" v-show="showVoice">
					<view class="voice-mode" @touchstart="voiceBegin" @touchmove.stop.prevent="voiceIng"
						@touchend="voiceEnd" @touchcancel="voiceCancel">{{recording?'松开 结束':'按住 说话'}}</view>
				</view>

				<view class="icon-mode">
					<!-- H5下不能录音，输入栏布局改动一下 -->
					<!-- #ifdef H5 -->
					<view class="icon biaoqing" @click="openEmojiMode"></view>
					<!-- #endif -->
					<!-- #ifndef H5 -->
					<view class="icon jianpan" @click="onTextareaFocus" v-if="showEmojiMode"></view>
					<view class="icon biaoqing" @click="openEmojiMode" v-else></view>
					<!-- #endif -->
				</view>
				<view class="icon-mode" v-if="!showVoice && textMsg" style="line-height: 70rpx;">
					<view class="btn btn-turquoise" @click="sendText">发送</view>
				</view>
				<view class="icon-mode" v-else>
					<view class="icon add" @click="openMoreMode"></view>
				</view>
			</view>

			<!-- 抽屉栏 -->
			<view class="popup-panel">
				<!-- 表情 -->
				<view class="emoji-mode" v-show="showEmojiMode">
					<view class="list">
						<view class="item" v-for="(item,index) in emojiList" :key="item.url">
							<image mode="widthFix" @click="addEmoji(item)" :src="item.url"></image>
						</view>
					</view>
				</view>

				<!-- 更多功能 相册-拍摄-视频通话 -->
				<view class="more-mode" v-show="showMoreMode">
					<view class="list">
						<view class="item">
							<view class="itemt" @click="chooseImage">
								<view class="icon-wrap">
									<view class="icon tupian2"></view>
								</view>
								<view class="txt-wrap">相册</view>
							</view>
						</view>
						<view class="item">
							<view class="itemt" @click="camera">
								<view class="icon-wrap">
									<view class="icon paizhao"></view>
								</view>
								<view class="txt-wrap">拍摄</view>
							</view>
						</view>
						<!-- <view class="item" v-if="cate=='report'&&isDoc==0"> -->
						<view class="item" v-if="orderInfo.is_sign==1&&isDoc==0">
							<view class="itemt" @click="baogaojiedu">
								<view class="icon-wrap">
									<image src="/static/chufang.png"></image>
								</view>
								<view class="txt-wrap">报告解读</view>
							</view>
						</view>
						<view class="item" v-if="cate=='video'">
							<view class="itemt" @click="videoCall">
								<view class="icon-wrap">
									<image src="/static/shipin.png"></image>
								</view>
								<view class="txt-wrap">视频通话</view>
							</view>
						</view>
						<view class="item" v-if="isDoc==1">
							<view class="itemt" @click="chufang">
								<view class="icon-wrap">
									<image src="/static/chufang.png"></image>
								</view>
								<view class="txt-wrap">开处方</view>
							</view>
						</view>
						<view class="item" v-if="isDoc==1">
							<view class="itemt" @click="consultationHistory">
								<view class="icon-wrap">
									<image src="/static/chufang.png"></image>
								</view>
								<view class="txt-wrap">历史就诊</view>
							</view>
						</view>
						<view class="item" v-if="isDoc==1">
							<view class="itemt" @click="yizhu">
								<view class="icon-wrap">
									<image src="/static/chufang.png"></image>
								</view>
								<view class="txt-wrap">开医嘱</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 录音UI效果 -->
		<view class="record" v-show="recording">
			<view class="ing" v-show="!willStop">
				<view class="ing-inner">
					<view class="icon luyin2"></view>
				</view>
			</view>
			<view class="cancel" v-show="willStop">
				<view class="cancel-inner">
					<view class="icon chehui"></view>
				</view>
			</view>
			<view class="tis" :class="willStop?'change':''">{{willStop?'松开手指 取消发送':'手指上滑 取消发送'}}</view>
		</view>

		<u-popup :show="showFilePop" :round="10" mode="center">
			<view class="popup-empty-file-content">
				<image class="close" src="/static/lj/drug/icon_close.png" mode="aspectFill" @click="showFilePop=false">
				</image>
				<view class="popup-title">暂无检测报告，是否前去检测？</view>
				<view class="popup-content u-flex u-flex-between">
					<view class="item">
						<view class="btn-fillet" @click="gotoMini(pwappid, pwpage)">去检测</view>
						<view class="tip">前往维普小程序检测</view>
					</view>
					<view class="item">
						<view class="btn-fillet-o" @click="uploadReport">上传报告</view>
						<view class="tip">已有其他机构检测报告</view>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<style lang="scss">
	// @import "@/static/message/static/HM-chat/css/style.scss";
	@import "chat.scss";
</style>

<script>
	export default {
		data() {
			return {
				pwappid: '',
				pwpage: '',
				jkscappid: '',
				jkscpage: '',

				orderInfo: null,
				orderStatus: -1, //0.待接诊

				no_patient_time_show: "",
				patient_time_show: "",
				waitTimestamp: 24 * 60 * 60, //待接诊时间
				consultTimestamp: 4 * 60 * 60, //咨询时间
				waitTimestampTimer: null,
				consultTimestampTimer: null,

				http_img: '',

				isDoc: 0,
				cate: "text",
				orderno: "",
				chatList: [],
				chatImgList: [],
				FromUser: {},
				ToUser: {},
				joinIm: false,
				imStatus: {
					// Socket连接状态
					IsOpen: false,
					// SocketTask
					SocketTask: false,
					// 是否上线
					IsOnline: false,
				},

				timePointerSize: 2 * 60, //2分钟时间范围内不增加时间显示
				timePointer: 0, //时间指针，用于是否显示时间
				downTimeTxt: "", //倒计时

				contentTop: 0,
				contentBottom: 0,
				contentInitBottom: 206,
				textareaFocus: true,
				textareaPrevLineCount: 1, //前一次的行高
				textareaAutoHeight: true, //文本输入框自增高
				showVoice: false, //显示录音
				showEmojiMode: false, //显示表情模块
				showMoreMode: false, //显示更多模块

				// 录音参数
				// #ifdef H5
				//H5不能录音
				RECORDER: null,
				// #endif
				// #ifndef H5
				//H5不能录音
				RECORDER: uni.getRecorderManager(),
				// #endif
				voiceBeginLock: false,
				recording: false,
				recordY: 0, //按住说话时的高度，用于上滑取消发送
				willStop: false,
				recordTimer: null, //录音计时器

				//播放语音相关参数
				AUDIO: uni.createInnerAudioContext(),
				playMsgid: null,

				//消息
				scrollAnimation: true,
				isHistoryLoading: false,
				scrollTop: 0,
				scrollToView: '',

				emojiList: [],

				textMsg: "",

				showCommentTip: true,

				showFilePop: false,

				callshow: false,
				videoObj: {}
			}
		},
		onLoad(option) { //只加载一次
			var that = this

			that.$Http({
				url: 'getOthMiniConfig',
				data: {},
				token: false
			}).then(res => {
				if (res.code == 1) {
					that.pwappid = res.data.pwappid
					that.pwpage = res.data.pwpage
					that.jkscappid = res.data.jkscappid
					that.jkscpage = res.data.jkscpage
				}
			});

			that.imStatus = {
					// Socket连接状态
					IsOpen: that.$store.state.IsOpen,
					// SocketTask
					SocketTask: that.$store.state.SocketTask,
					// 是否上线
					IsOnline: that.$store.state.IsOnline,
				},
				uni.$on("onImStatus", (rel) => {
					console.log('==>>我被全局通知了onImStatus', rel)
					that.imStatus = rel

					if (!that.imStatus.IsOpen) {
						uni.showLoading({
							title: '正在连接聊天室...',
							mask: true
						});
					} else {
						uni.hideLoading()

						// if(!that.joinIm){
						// 	console.log('chatdebug', 111)
						// 	if(that.imStatus.IsOnline){
						// 		console.log('chatdebug', 222)
						// 		uni.hideLoading()
						// 		if(that.orderInfo){
						// 			that.emojiList = that.$store.state.emojiData
						// 			that.chatInit(that.orderInfo)
						// 		}
						// 	}
						// }else if(!that.orderInfo.doctor_info){
						// 	console.log('chatdebug', 333)
						if (that.imStatus.code == 'bind') that.init()
						// }
					}
				})

			that.http_img = that.$store.state.http_img
			that.emojiList = that.$store.state.emojiData
			// if(option.isDoc==1 && this.$store.state.userDoc.uid==0) return false;
			that.isDoc = option.isDoc == 1 ? 1 : 0;
			that.cate = option.cate
			that.orderno = option.orderno
			console.log('chat~')

			that.init()
		},
		onShow: function() {},
		onReady() { //只加载一次
		},
		onHide() {
			console.log('监听页面隐藏');
		},
		onUnload() {
			console.log('监听页面卸载');
			this.$store.commit('closeToUser')
			uni.$off("onImStatus")
			uni.$off("UserChat")
			if (this.waitTimestampTimer) {
				clearInterval(this.waitTimestampTimer)
				this.waitTimestampTimer = null
			}
			if (this.consultTimestampTimer) {
				clearInterval(this.consultTimestampTimer)
				this.consultTimestampTimer = null
			}
		},
		methods: {
			gotoMini(appid, page) {
				uni.navigateToMiniProgram({
					appId: appid,
					path: page,
					success(e) {
						console.log('gotoMini', e)
					},
					fail(e) {
						console.log('gotoMini fail', e)
					}
				})
			},
			sendMsg(type, content) {
				this.$store.dispatch('sendChatMessage', {
					cate: this.cate,
					orderno: this.orderno,
					type: type,
					content: content
				})
			},
			init() {
				var that = this
				// ~~~~ 测试参数 后期删除或注释
				// this.isDoc=1
				// this.cate='text'
				// this.orderno='2108190410495808871426'
				// ~~~~

				that.contentTop = that.isDoc == 0 ? 80 : 190

				console.log('====================出的this.cate', this.cate)
				if (this.cate == 'text') { //图文问诊
					this.$Http({
						url: this.isDoc ? 'doctordetailsConsultationOrder' : 'detailsConsultationOrder',
						type: 'POST',
						data: {
							order_code: this.orderno
						}
					}).then(res => {
						if (res.code == 1) that.chatInit(res.data)
						else {
							uni.showToast({
								icon: 'none',
								duration: 3000,
								title: res.msg
							});
						}
					})
				} else if (this.cate == 'video') { //视频问诊
					that.$Http({
						url: 'getConsultationInfo',
						data: {
							order_code: that.orderno
						}
					}).then(res => {
						if (res.code == 1) {
							res.data.doctor_img = that.$Config.http_static + res.data.data.doctor_img,
							this.videoObj = res.data.data
						}
					})
					wx.setEnable1v1Chat({
						enable: true,
						success(res) {
							that.callshow = true
						},
						fail(err) {
							that.callshow = false
						}
					})
					this.$Http({
						url: this.isDoc ? 'doctordetailsConsultationVideoOrder' : 'detailsConsultationVideoOrder',
						type: 'POST',
						data: {
							order_code: this.orderno
						}
					}).then(res => {
						if (res.code == 1) that.chatInit(res.data)
						else {
							uni.showToast({
								icon: 'none',
								duration: 3000,
								title: res.msg
							});
						}
					})
				} else if (this.cate == 'report') { //报告解读
					this.$Http({
						url: this.isDoc ? 'doctordetailsConsultationReportOrder' :
							'detailsConsultationReportOrder',
						type: 'POST',
						data: {
							order_code: this.orderno
						}
					}).then(res => {
						if (res.code == 1) that.chatInit(res.data)
						else {
							uni.showToast({
								icon: 'none',
								duration: 3000,
								title: res.msg
							});
						}
					})
				} else {
					uni.showToast({
						icon: 'none',
						duration: 3000,
						title: '参数错误.'
					});
				}
			},
			chatInit(orderInfo) {
				uni.$off("UserChat")
				console.debug("正在连接聊天室...")
				var that = this
				if (!orderInfo) {
					uni.showToast({
						icon: 'none',
						duration: 3000,
						title: '问诊订单不存在~'
					});
					return false
				}
				that.orderInfo = orderInfo;
				// 未付款的订单查询不到

				if (!that.imStatus.IsOnline) {
					uni.showLoading({
						title: '正在连接聊天室...',
						mask: true
					});
					return false
				}
				that.joinIm = true

				orderInfo.user_the_patient_info = orderInfo.user_the_patient_info ? orderInfo.user_the_patient_info :
					orderInfo.user_the_patient
				if (orderInfo.user_the_patient_info) orderInfo.user_the_patient_info.age = that.$base.Onage(orderInfo
					.user_the_patient_info.birthday)
				that.no_patient_time_show = that.formatSeconds(that.orderInfo.no_patient_time_config, {
					h: '小时',
					i: '分钟',
					s: '秒'
				}, false)
				that.patient_time_show = that.formatSeconds(that.orderInfo.patient_time_config, {
					h: '小时',
					i: '分钟',
					s: '秒'
				}, false)

				// ~~~~ 测试参数 后期删除或注释
				// orderInfo.pay_time = Date.parse(new Date())/1000
				// ~~~~

				// 配置发送方和接收方
				// that.FromUser = that.isDoc==1?that.$store.state.userDoc:that.$store.state.user
				// that.ToUser = {
				// 	prefix: that.isDoc==1?"HZ":"DT",
				// 	uid: that.uid,
				// 	nick: that.nick,
				// 	avatar: that.avatar
				// }
				if (that.isDoc == 1) {
					that.FromUser = that.$store.state.userDoc
					that.ToUser = {
						prefix: "HZ",
						uid: that.orderInfo.user_info ? that.orderInfo.user_info.id : that.orderInfo.user_id,
						// nick: that.orderInfo.user_info.nickname,
						nick: that.orderInfo.user_info ? that.orderInfo.user_the_patient_info.name : that.orderInfo
							.user_name,
						avatar: that.orderInfo.user_info ? that.orderInfo.user_info.headimgurl : that.orderInfo
							.user_headimgurl
					}
					uni.setNavigationBarTitle({
						title: '患者 - ' + that.ToUser.nick
					});
				} else {
					that.FromUser = that.$store.state.user
					that.FromUser.nick = that.orderInfo.user_the_patient_info.name
					if (that.orderInfo.doctor_info) {
						that.ToUser = {
							prefix: "DT",
							uid: that.orderInfo.doctor_info.user_id,
							nick: that.orderInfo.doctor_info.name,
							avatar: that.$store.state.http_img + that.orderInfo.doctor_info.img
						}
						uni.setNavigationBarTitle({
							title: that.ToUser.nick + '医生'
						});
					} else if (that.orderInfo.is_grab) {
						uni.setNavigationBarTitle({
							title: '极速问诊'
						});
					} else {
						uni.setNavigationBarTitle({
							title: '详情'
						});
					}
				}
				console.log('>>>> createToUser: ', that.FromUser, that.ToUser, that.$store.state)

				// pay_status 支付状态1-已支付,2-未支付
				// status 状态:normal=正常,refund=已退款,cancel=已取消,refuse_patient=拒绝接诊,patient=接诊,end=完成接诊,comment=已评论
				// that.orderStatus = -4 //待支付
				// that.orderStatus = -3 //已取消，医生接诊超时
				// that.orderStatus = -2 //已取消，用户主动取消
				// that.orderStatus = -1 //医生拒绝接诊
				// that.orderStatus = 0 //待接诊
				// that.orderStatus = 1 //咨询/接诊中
				// that.orderStatus = 2 //问诊结束
				switch (orderInfo.status) {
					case 'normal': //正常
						that.orderStatus = 0 //待接诊
						if (orderInfo.pay_status == 2) that.orderStatus = -4 //待支付
						else if (orderInfo.no_patient_timing <= 0) that.orderStatus = -3 //已取消，用户主动取消
						break;
					case 'patient': //接诊
						that.orderStatus = 1 //咨询/接诊中
						if (orderInfo.patient_timing <= 0) that.orderStatus = 2 //问诊结束
						break;
					case 'refuse_patient': //拒绝接诊
						that.orderStatus = -1 //医生拒绝接诊
						break;
					case 'end': //完成接诊
						that.orderStatus = 2 //问诊结束
						break;
					case 'comment': //已评论
						that.orderStatus = 2 //问诊结束
						break;
					case 'cancel': //已取消
						// that.orderStatus = -3 //已取消，医生接诊超时
						that.orderStatus = -2 //已取消，用户主动取消
						break;
					case 'refund': //已退款
						// that.orderStatus = -3 //已取消，医生接诊超时
						that.orderStatus = -2 //已取消，用户主动取消
						break;
				}

				if (that.orderStatus == 0) that.waitTimestampDown() //待接诊倒计时
				if (that.orderStatus == 1) {
					that.consultTimestampDown() //咨询中倒计时
					that.contentBottom = that.isDoc == 1 ? that.contentInitBottom : that.contentInitBottom - 84
				}

				if (that.orderStatus <= 0) that.consultationMsg()
				else that.getChatHistory()

				that.$store.commit('createToUser', {
					FromUser: that.FromUser,
					ToUser: that.ToUser,
					orderno: that.orderno
				})

				that.$store.dispatch('readChatMessage', {
					cate: that.cate,
					orderno: that.orderno,
					uid: that.ToUser.uid,
					noread: 1,
					isDoc: that.isDoc == 1 ? 1 : 0
				})
				uni.$on("UserChat", (rel) => {
					console.log('》》》》 我被全局通知了UserChat', rel)
					if (!that.orderInfo.doctor_info) {
						uni.$off("UserChat");
						that.init();
					} else if (rel.type != "consultationHandle") {
						that.$store.dispatch('readChatMessage', {
							cate: that.cate,
							orderno: that.orderno,
							uid: that.ToUser.uid,
							noread: 1,
							isDoc: that.isDoc == 1 ? 1 : 0
						})
						if (!rel.notRender) {
							// that.chatList = rel
							console.log('》》》》 需要渲染到会话窗口')
							var cf = that.FromUser.prefix + that.FromUser.uid + that.cate + that.orderno
							var ct = that.ToUser.prefix + that.ToUser.uid + that.cate + that.orderno
							var rf = rel.from.prefix + rel.from.uid + rel.cate + rel.orderno
							if (ct == rf || cf == rf) {
								if (rel.time - that.timePointer > that.timePointerSize) { //时间范围内不增加时间显示
									that.chatList.push({
										cate: that.cate,
										orderno: that.orderno,
										fromType: 'system',
										type: 'time',
										content: {
											text: that.$base.__formatTime(rel.time)
										},
									})
								}
								that.timePointer = rel.time

								if (rel.type == 'img') {
									that.chatImgList.push(rel.content.url)
								}
								if (rel.type == 'imgs') {
									if (idx < 0) idx = i

									for (var j in rel.content.list) {
										that.chatImgList.push(rel.content.list[j].url)
									}
								}

								that.chatList.push(rel)

								that.$nextTick(function() {
									that.scrollToView = "chat-" + (that.chatList.length - 1)
								})
							}
						} else {
							console.log('》》》》 不需要渲染到会话窗口')
						}
					} else {
						console.log('》》》》 这是对方的操作通知')
						// 判断是否为当前会话
						// var cf = that.FromUser.prefix+that.FromUser.uid+that.cate+that.orderno
						var ct = that.ToUser.prefix + that.ToUser.uid + that.cate + that.orderno
						var rf = rel.from.prefix + rel.from.uid + rel.cate + rel.orderno
						// var rt = rel.to.prefix+rel.to.uid+rel.cate+rel.orderno

						if (ct == rf) {
							console.log("是当前会话的消息")
							that.orderStatus = rel.content.orderStatus
							if (rel.content.code == 'receivePatient') {
								that.orderInfo.patient_timing = rel.content.patient_timing
								that.chatList.push({
									cate: that.cate,
									orderno: that.orderno,
									fromType: 'system',
									type: 'tip',
									content: {
										text: "问诊已开始，本次问诊可持续" + that.patient_time_show
									},
								})

								if (that.waitTimestampTimer) {
									clearInterval(that.waitTimestampTimer)
									that.waitTimestampTimer = null
								}
								that.orderInfo.patient_time = rel.time
								that.consultTimestampDown()
							} else if (rel.content.code == 'endPatient') {
								that.contentBottom = 0
							}
						} else {
							console.log("不是当前会话的消息")
						}
					}
				})

				//语音自然播放结束
				that.AUDIO.onEnded((res) => {
					that.playMsgid = null;
					console.log('语音播放结束')
				});
				that.AUDIO.onError((err) => {
					that.playMsgid = null;
					console.log('语音播放错误', err)
				});
				// #ifndef H5
				//录音开始事件
				that.RECORDER.onStart((e) => {
					// that.recordBegin(e);
				})
				//录音结束事件
				that.RECORDER.onStop((e) => {
					that.recordEnd(e);
				})
				// #endif
			},
			// 待接诊倒计时 23小时45分
			waitTimestampDown() {
				var that = this
				that.waitTimestamp = that.orderInfo.no_patient_timing
				that.downTimeTxt = that.formatSeconds(that.waitTimestamp, {
					h: '小时',
					i: '分',
					s: '秒'
				}, true)
				if (that.waitTimestamp > 0) {
					if (that.waitTimestampTimer) {
						clearInterval(that.waitTimestampTimer)
						that.waitTimestampTimer = null
					}
					that.waitTimestampTimer = setInterval(function() {
						that.waitTimestamp--
						that.downTimeTxt = that.formatSeconds(that.waitTimestamp, {
							h: '小时',
							i: '分',
							s: '秒'
						}, true)
						if (that.waitTimestamp <= 0) {
							clearInterval(that.waitTimestampTimer)
							that.waitTimestampTimer = null
							that.refusePatientExpire()
						}
					}, 1000)
				}
			},
			// 咨询中倒计时 01:21:00
			consultTimestampDown() {
				var that = this
				that.consultTimestamp = that.orderInfo.patient_timing
				console.log('咨询中倒计时')
				that.downTimeTxt = that.formatSeconds(that.consultTimestamp, {
					h: ':',
					i: ':',
					s: ''
				}, true)
				if (that.consultTimestamp > 0) {
					if (that.consultTimestampTimer) {
						clearInterval(that.consultTimestampTimer)
						that.consultTimestampTimer = null
					}
					that.consultTimestampTimer = setInterval(function() {
						that.consultTimestamp--
						that.downTimeTxt = that.formatSeconds(that.consultTimestamp, {
							h: ':',
							i: ':',
							s: ''
						}, true)
						if (that.consultTimestamp <= 0) {
							clearInterval(that.consultTimestampTimer)
							that.consultTimestampTimer = null
							that.orderStatus = 2
							that.contentBottom = 0
						}
					}, 1000)
				}
			},
			// 拒绝接诊
			refusePatient() {
				var that = this
				if (that.cate == 'text') { //图文问诊
					uni.showModal({
						title: '操作提示',
						confirmText: '确定',
						confirmColor: '#6bcbb6',
						cancelText: '取消',
						content: '您确定拒绝接诊吗',
						success: function(res) {
							if (res.confirm) {
								that.$Http({
									url: 'consultationRefusePatient',
									type: 'POST',
									show: true,
									data: {
										order_id: that.orderInfo.id
									}
								}).then(res => {
									if (res.code == 1) {
										that.orderStatus = -1
										that.sendMsg('consultationHandle', {
											code: "refusePatient",
											orderStatus: that.orderStatus
										})
									}
								})
							}
						},
					})
				} else if (that.cate == 'video') { //视频问诊
					uni.showModal({
						title: '操作提示',
						confirmText: '确定',
						confirmColor: '#6bcbb6',
						cancelText: '取消',
						content: '您确定拒绝接诊吗',
						success: function(res) {
							if (res.confirm) {
								that.$Http({
									url: 'consultationVideoRefusePatient',
									type: 'POST',
									show: true,
									data: {
										order_id: that.orderInfo.id
									}
								}).then(res => {
									if (res.code == 1) {
										that.orderStatus = -1
										that.sendMsg('consultationHandle', {
											code: "refusePatient",
											orderStatus: that.orderStatus
										})
									}
								})
							}
						},
					})
				} else if (that.cate == 'report') { //报告解读
					uni.showModal({
						title: '操作提示',
						confirmText: '确定',
						confirmColor: '#6bcbb6',
						cancelText: '取消',
						content: '您确定拒绝接诊吗',
						success: function(res) {
							if (res.confirm) {
								that.$Http({
									url: 'consultationReportRefusePatient',
									type: 'POST',
									show: true,
									data: {
										order_id: that.orderInfo.id
									}
								}).then(res => {
									if (res.code == 1) {
										that.orderStatus = -1
										that.sendMsg('consultationHandle', {
											code: "refusePatient",
											orderStatus: that.orderStatus
										})
									}
								})
							}
						},
					})
				} else {
					uni.showToast({
						icon: 'none',
						duration: 3000,
						title: '参数错误..'
					});
				}
			},
			// 到时未接诊
			refusePatientExpire() {
				var that = this
				that.orderStatus = -3
				if (that.cate == 'text') { //图文问诊
					that.orderStatus = -3
				} else if (that.cate == 'video') { //视频问诊
					that.orderStatus = -3
				} else if (that.cate == 'report') { //报告解读
					that.orderStatus = -3
				}
			},
			// 接诊
			receivePatient() {
				var that = this
				if (that.cate == 'text') { //图文问诊
					uni.showModal({
						title: '操作提示',
						confirmText: '确定',
						confirmColor: '#6bcbb6',
						cancelText: '取消',
						content: '您确定要接诊吗',
						success: function(res) {
							if (res.confirm) {
								that.$Http({
									url: 'consultationPatient',
									type: 'POST',
									show: true,
									data: {
										order_id: that.orderInfo.id
									}
								}).then(res => {
									if (res.code == 1) {
										that.orderInfo.patient_timing = res.data
										that.receiveSuccess()
									}
								})
							}
						},
					})
				} else if (that.cate == 'video') { //视频问诊
					uni.showModal({
						title: '操作提示',
						confirmText: '确定',
						confirmColor: '#6bcbb6',
						cancelText: '取消',
						content: '您确定要接诊吗',
						success: function(res) {
							if (res.confirm) {
								that.$Http({
									url: 'consultationVideoPatient',
									type: 'POST',
									show: true,
									data: {
										order_id: that.orderInfo.id
									}
								}).then(res => {
									that.orderInfo.patient_timing = res.data
									if (res.code == 1) that.receiveSuccess()
								})
							}
						},
					})
				} else if (that.cate == 'report') { //报告解读
					uni.showModal({
						title: '操作提示',
						confirmText: '确定',
						confirmColor: '#6bcbb6',
						cancelText: '取消',
						content: '您确定要接诊吗',
						success: function(res) {
							if (res.confirm) {
								that.$Http({
									url: 'consultationReportPatient',
									type: 'POST',
									show: true,
									data: {
										order_id: that.orderInfo.id
									}
								}).then(res => {
									if (res.code == 1) {
										that.orderInfo.patient_timing = res.data
										that.receiveSuccess()
									}
								})
							}
						},
					})
				} else {
					uni.showToast({
						icon: 'none',
						duration: 3000,
						title: '参数错误...'
					});
				}
			},
			// 接诊成功
			receiveSuccess() {
				var that = this
				that.orderStatus = 1

				// 向患者发送接诊通知
				that.sendMsg('consultationHandle', {
					code: "receivePatient",
					orderStatus: that.orderStatus,
					patient_timing: that.orderInfo.patient_timing,
					chatList: that.chatList
				})
				that.chatList.push({
					cate: that.cate,
					orderno: that.orderno,
					fromType: 'system',
					type: 'tip',
					content: {
						text: "问诊已开始，本次问诊可持续" + that.patient_time_show
					},
				})
				if (that.waitTimestampTimer) {
					clearInterval(that.waitTimestampTimer)
					that.waitTimestampTimer = null
				}
				that.orderInfo.patient_time = Date.parse(new Date()) / 1000
				that.consultTimestampDown()
			},
			// 完成接诊
			endPatient() {
				var that = this
				if (that.cate == 'text') { //图文问诊
					uni.showModal({
						title: '操作提示',
						confirmText: '确定',
						confirmColor: '#6bcbb6',
						cancelText: '取消',
						content: '您确定要完成接诊吗',
						success: function(res) {
							if (res.confirm) {
								that.$Http({
									url: 'consultationEndPatient',
									type: 'POST',
									show: true,
									data: {
										order_id: that.orderInfo.id
									}
								}).then(res => {
									if (res.code == 1) {
										that.orderStatus = 2
										that.sendMsg('consultationHandle', {
											code: "endPatient",
											orderStatus: that.orderStatus
										})

										that.contentBottom = 0
									}
								})
							}
						},
					})
				} else if (that.cate == 'video') { //视频问诊
					uni.showModal({
						title: '操作提示',
						confirmText: '确定',
						confirmColor: '#6bcbb6',
						cancelText: '取消',
						content: '您确定要完成接诊吗',
						success: function(res) {
							if (res.confirm) {
								that.$Http({
									url: 'videoEndPatient',
									type: 'POST',
									show: true,
									data: {
										order_id: that.orderInfo.id
									}
								}).then(res => {
									console.log(res)
									if (res.code == 1) {
										that.orderStatus = 2
										that.sendMsg('consultationHandle', {
											code: "endPatient",
											orderStatus: that.orderStatus
										})

										that.contentBottom = 0
									}
								})
							}
						},
					})
				} else if (that.cate == 'report') { //报告解读
					uni.showModal({
						title: '操作提示',
						confirmText: '确定',
						confirmColor: '#6bcbb6',
						cancelText: '取消',
						content: '您确定要完成接诊吗',
						success: function(res) {
							if (res.confirm) {
								that.$Http({
									url: 'reportEndPatient',
									type: 'POST',
									show: true,
									data: {
										order_id: that.orderInfo.id
									}
								}).then(res => {
									console.log(res)
									if (res.code == 1) {
										that.orderStatus = 2
										that.sendMsg('consultationHandle', {
											code: "endPatient",
											orderStatus: that.orderStatus
										})

										that.contentBottom = 0
									}
								})
							}
						},
					})
				} else {
					uni.showToast({
						icon: 'none',
						duration: 3000,
						title: '参数错误....'
					});
				}
			},

			// 取消
			refundOrder() {
				var that = this
				if (that.cate == 'text') { //图文问诊
					uni.showModal({
						title: '操作提示',
						confirmText: '确定',
						confirmColor: '#6bcbb6',
						cancelText: '取消',
						content: '您确定要取消问诊吗',
						success: function(res) {
							if (res.confirm) {
								that.$Http({
									url: 'refundConsultationOrder',
									data: {
										order_code: that.orderInfo.order_code,
									},
									show: true,
									type: 'post'
								}).then(res => {
									if (res.code == 1) {
										that.orderStatus = -2
										that.sendMsg('consultationHandle', {
											code: "refundOrder",
											orderStatus: that.orderStatus
										})
									}
								})
							}
						}
					});
				} else if (that.cate == 'video') { //视频问诊
					uni.showModal({
						title: '操作提示',
						confirmText: '确定',
						confirmColor: '#6bcbb6',
						cancelText: '取消',
						content: '您确定要取消问诊吗',
						success: function(res) {
							if (res.confirm) {
								that.$Http({
									url: 'refundConsultationVideoOrder',
									data: {
										order_code: that.orderInfo.order_code,
									},
									show: true,
									type: 'post'
								}).then(res => {
									if (res.code == 1) {
										that.orderStatus = -2
										that.sendMsg('consultationHandle', {
											code: "refundOrder",
											orderStatus: that.orderStatus
										})
									}
								})
							}
						}
					});
				} else if (that.cate == 'report') { //报告解读
					uni.showModal({
						title: '操作提示',
						confirmText: '确定',
						confirmColor: '#6bcbb6',
						cancelText: '取消',
						content: '您确定要取消问诊吗',
						success: function(res) {
							if (res.confirm) {
								that.$Http({
									url: 'refundConsultationReportOrder',
									data: {
										order_code: that.orderInfo.order_code,
									},
									show: true,
									type: 'post'
								}).then(res => {
									if (res.code == 1) {
										that.orderStatus = -2
										that.sendMsg('consultationHandle', {
											code: "refundOrder",
											orderStatus: that.orderStatus
										})
									}
								})
							}
						}
					});
				}
			},

			// 输入框增高，最高5行
			autoHeight(e) {
				if (this.textareaPrevLineCount < e.detail.lineCount) { //增高
					if (e.detail.lineCount < 5) this.textareaAutoHeight = true;
					else this.textareaAutoHeight = false;
				} else { //减高
					if (e.detail.lineCount <= 5) this.textareaAutoHeight = true;
					else this.textareaAutoHeight = false;
				}
				this.textareaPrevLineCount = e.detail.lineCount
			},
			//获取焦点，如果不是选表情ing,则关闭抽屉
			onTextareaFocus() {
				if (this.orderStatus != 1) return
				// if(this.popupLayerClass=='showLayer' && this.hideMore == false){
				this.textareaFocus = true
				this.showVoice = false
				this.showEmojiMode = false
				this.showMoreMode = false

				if (this.orderStatus == 1) this.contentBottom = this.isDoc == 1 ? this.contentInitBottom : this
					.contentInitBottom - 84
				else this.contentBottom = 0
				// }
			},
			openVoice() {
				this.showVoice = true
				this.showEmojiMode = false
				this.showMoreMode = false
			},
			openEmojiMode() {
				var that = this
				this.showVoice = false
				this.showEmojiMode = this.showEmojiMode ? false : true
				this.showMoreMode = false

				this.contentBottom = this.showEmojiMode ? (this.contentInitBottom + 380) : this.contentInitBottom
				that.$nextTick(function() {
					that.scrollToView = "chat-" + (that.chatList.length - 1)
				})
			},
			openMoreMode() {
				var that = this
				this.showVoice = false
				this.showEmojiMode = false
				this.showMoreMode = this.showMoreMode ? false : true

				this.contentBottom = this.showMoreMode ? (this.contentInitBottom + 260) : this.contentInitBottom
				that.$nextTick(function() {
					that.scrollToView = "chat-" + (that.chatList.length - 1)
				})
			},
			addEmoji(item) {
				console.log(item)
				this.textMsg += item.alt;
			},

			voiceBegin(e) {
				if (this.voiceBeginLock) return;
				if (e.touches.length > 1) return;
				console.log('recordBegin', touche, e)

				var that = this

				let touche = e.touches[0];
				this.recordY = touche.clientY
				// this.recordTimer = setTimeout(()=>{
				if (that.RECORDER) {
					that.voiceBeginLock = true
					that.RECORDER.start({
						format: "mp3"
					}); //录音开始,
				}
				that.recordBegin()
				// },300)
			},
			voiceIng(e) {
				if (!this.recording) return;
				console.log('voiceIng', touche, e)

				let touche = e.touches[0];
				//上滑一个导航栏的高度触发上滑取消发送
				if (this.recordY - touche.clientY >= 50) {
					this.willStop = true;
				} else {
					this.willStop = false;
				}
			},
			voiceEnd(e) {
				console.log('voiceEnd debug')
				// clearInterval(this.recordTimer);
				if (!this.recording) return;
				console.log('voiceEnd')

				var that = this
				setTimeout(() => {
					that.recording = false;
					if (that.RECORDER) that.RECORDER.stop(); //录音结束
					else that.recordEnd()
				}, 1500)
			},
			voiceCancel(e) {
				console.log('voiceCancel')

				this.recording = false;
				this.willStop = true; //不发送录音
				if (this.RECORDER) this.RECORDER.stop(); //录音结束
				else this.recordEnd()
			},
			//录音开始UI效果
			recordBegin(e) {
				this.recording = true
				this.willStop = false;
			},
			//录音结束(回调文件)
			recordEnd(e) {
				console.log('recordEnd', e)
				let that = this
				that.voiceBeginLock = false
				if (!this.willStop) {
					if (e.duration >= 2000) {
						// console.log("e: " + JSON.stringify(e));
						uni.uploadFile({
							url: that.$Config.http_static + 'api/common/uploader',
							filePath: e.tempFilePath,
							name: 'file',
							formData: {},
							success: (uploadFileRes) => {
								var obj = JSON.parse(uploadFileRes.data);
								if (obj.msg = "上传成功") {
									let msg = {
										url: obj.data.fullurl,
										length: 0,
									}
									let min = parseInt(parseInt(e.duration / 1000) / 60);
									let sec = parseInt(e.duration / 1000) % 60;
									min = min < 10 ? '0' + min : min;
									sec = sec < 10 ? '0' + sec : sec;
									msg.length = min + ':' + sec;
									this.sendMsg('voice', msg);
								}
							}
						});
					} else {
						uni.showToast({
							icon: 'none',
							duration: 3000,
							title: '说话时间太短'
						});
					}
				} else {
					// console.log('取消发送录音');
				}
				this.willStop = false;
			},
			// 播放语音
			playVoice(item, index) {
				console.log(item, index)
				if (this.playMsgid == index) {
					this.AUDIO.stop();
					this.playMsgid = null;
					return
				}
				this.playMsgid = index;
				this.AUDIO.src = item.content.url;
				// this.$nextTick(function() {
				this.AUDIO.play();
				// });
			},

			// 触发滑动到顶部(加载历史记录)
			loadHistory(e) {
				return
				if (this.isHistoryLoading) return
				var that = this

				this.isHistoryLoading = true; //参数作为进入请求标识，防止重复请求
				this.scrollAnimation = false; //关闭滑动动画

				// if(this.msgList == []){
				// 	let Viewid = 0;
				// }else{
				// 	let Viewid = this.msgList[0].msg.id;//记住第一个信息ID
				// }
				setTimeout(function() {
					that.scrollAnimation = true; //恢复滚动动画
					that.isHistoryLoading = false;
				}, 3000)
			},

			// 发送文字消息
			sendText() {
				if (!this.textMsg) return;

				let content = this.replaceEmoji(this.textMsg);
				let msg = {
					text: content,
					_text: this.textMsg
				}
				this.sendMsg('text', msg)
				this.textMsg = '' //清空输入框
				this.onTextareaFocus()
			},
			// 发图片
			chooseImage() {
				this.getImage('album');
			},
			// 拍照
			camera() {
				this.getImage('camera');
			},
			//选照片 or 拍照
			getImage(type) {
				var that = this
				uni.chooseImage({
					sourceType: [type],
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					success: (res) => {
						for (let i = 0; i < res.tempFilePaths.length; i++) {
							uni.uploadFile({
								url: that.$Config.http_static + 'api/common/uploader',
								filePath: res.tempFilePaths[i],
								name: 'file',
								formData: {},
								success: (uploadFileRes) => {
									var obj = JSON.parse(uploadFileRes.data);
									if (obj.msg = "上传成功") that.sendMsg('img', {
										url: obj.data.fullurl,
										w: 500,
										h: 500
									});
								}
							});
						}
					}
				});
			},
			// 视频通话
			videoCall() {
				let that = this
				if (this.callshow) {
					wx.join1v1Chat({
						// 接听方信息
						listener: {
							nickname: !this.isDoc ? that.videoObj.doctor_name : that.videoObj.patient_name,
							// headImage: !this.isDoc ? that.videoObj.doctor_img : that.videoObj.patient_img,
							openid: !this.isDoc ? that.videoObj.doctor_openid : that.videoObj.patient_openid,
						},
						// 呼叫方信息
						caller: {
							nickname: this.isDoc ? that.videoObj.doctor_name : that.videoObj.patient_name,
							// headImage: this.isDoc ? that.videoObj.doctor_img : that.videoObj.patient_img,
							openid: this.isDoc ? that.videoObj.doctor_openid : that.videoObj.patient_openid,
						},
						success(res) {
							// console.log(res, '成功~')
						},
						fail(err) {
							uni.showToast({
								icon: 'none',
								duration: 3000,
								title: '视频通话失败~'
							});
						}
					})
				} else {
					uni.showToast({
						icon: 'none',
						duration: 3000,
						title: '视频通话失败'
					});
				}
				// this.sendMsg('video', {});
				// uni.navigateTo({
				// 	url: '/pagesA/common/video?id=' + this.orderInfo.id + '&type='+(this.isDoc==1?'doc':'user'),
				// })
				// that.$store.dispatch('sendChatMessage',{cate:that.cate, orderno:res.data.orderno, type:'consultationHandle', content:{
				// 	code: "prescript",
				// 	cf_id: res.data.id,
				// }})
				// let t = '我已进入视频聊天~'
				// let content = this.replaceEmoji(t);
				// let msg = {text:content,_text:t}
				// this.sendMsg('text', msg)
				// uni.navigateTo({
				// 	url: '/pagesA/common/video?id=' + this.orderInfo.id + '&type='+(this.isDoc==1?'doc':'user'),
				// })
			},
			// 开处方
			chufang() {
				this.onTextareaFocus()
				uni.navigateTo({
					url: '/pagesA/prescript/list?cate=' + this.cate + '&consultation_id=' + this.orderInfo.id +
						'&familyId=' + this.orderInfo.user_the_patient_info.id + '&doctorId=' + this.FromUser.uid,
				})
			},
			// 历史就诊 - 医生
			consultationHistory() {
				this.onTextareaFocus()
				uni.navigateTo({
					url: '/pagesD/doctor/consultationHistory?familyId=' + this.orderInfo.user_the_patient_info.id +
						'&userId=' + this.orderInfo.user_id,
				})
			},
			// 医嘱 - 医生
			yizhu() {
				this.onTextareaFocus()
				uni.navigateTo({
					url: '/pagesA/prescript/newAdvice?cate='+this.cate+'&consultation_id='+this.orderInfo.id+'&familyId=' + this.orderInfo.user_the_patient_info.id + '&doctorId=' + this.FromUser.uid+'&userId=' + this.orderInfo.user_id,
				})
			},
			// 报告解读
			baogaojiedu() {
				this.showFilePop = true
			},
			uploadReport() {
				var that = this
				wx.chooseMessageFile({
					count: 1,
					type: 'file',
					extension: ['pdf'],
					success(res) {
						console.log(res)
						var tempFiles = res.tempFiles
						if (!tempFiles || tempFiles.length <= 0) {
							that.$u.toast("选取文件失败.")
							return false
						}
						uni.showLoading({
							title: '上传中',
							mask: true
						})
						uni.uploadFile({
							url: that.$Config.http_static + 'api/common/uploader',
							filePath: tempFiles[0].path,
							name: 'file',
							formData: {},
							success: (uploadFileRes) => {
								uni.hideLoading()
								console.log('uploadReport uploadFile', uploadFileRes)
								var obj = JSON.parse(uploadFileRes.data);
								console.log('uploadReport uploadFile', obj)
								if (obj.msg = "上传成功") {
									that.showFilePop = false
									that.sendMsg('file', {
										type: 'pdf',
										name: tempFiles[0].name,
										url: obj.data.fullurl,
										time: that.$u.timeFormat(tempFiles[0].time,
											'yyyy-mm-dd hh:MM')
									});
								} else {
									that.$u.toast('上传失败');
								}
							},
							fail(e) {
								console.log('uploadReport uploadFile fail', e)
								uni.hideLoading()
								that.$u.toast('上传失败');
							}
						})
					},
					fail(e) {
						console.log("chooseMessageFile fail ", e);
						that.$u.toast("选取文件失败")
					}
				})
			},



			// 预览图片
			showPic(item) {
				uni.previewImage({
					indicator: "none",
					current: item.url,
					urls: this.chatImgList
				});
			},
			// 跳转
			toHz() {
				var type = 'text'
				if (this.cate == 'text') type = 'tw'
				else if (this.cate == 'video') type = 'sp'
				else if (this.cate == 'report') type = 'report'
				uni.navigateTo({
					url: '/pagesA/doctor/textinfo?type=' + type + '&id=' + this.orderInfo.id,
				})
			},
			toDrug(chat_id, cf_id) {
				if (!this.isDoc) return false;
				uni.navigateTo({
					url: '/pagesA/prescript/doctorOrderDetail?id=' + cf_id + '&chat_id=' + chat_id,
				})
			},
			toPj() {
				var type = 'tw'
				if (this.cate == 'video') type = 'sp'
				else if (this.cate == 'report') type = 'report'
				uni.navigateTo({
					url: '/pagesA/common/evaluate?type=' + type + '&id=' + this.orderInfo.id,
				})
			},
			// 再次复诊
			restoration() {
				uni.navigateTo({
					url: '/pagesA/ask/inquiry?id=' + this.orderInfo.doctor_id + '&family_id=' + this.orderInfo
						.the_patient_id,
				})
			},

			getChatHistory() {
				var that = this
				this.$Http({
					url: 'chatHistory',
					type: 'POST',
					show: true,
					data: {
						orderno: this.orderno,
						isDoc: this.isDoc,
						cate: this.cate
					}
				}).then(res => {
					if (res.code == 1) {
						var chatList = [];
						var idx = -1;
						for (var i in res.data) {
							try {
								var chat = JSON.parse(res.data[i].message).msg;
								chat.log_id = res.data[i].log_id
								console.log(chat)
								if (chat.time - that.timePointer > that.timePointerSize) { //时间范围内不增加时间显示
									chatList.push({
										log_id: 0,
										cate: that.cate,
										orderno: that.orderno,
										fromType: 'system',
										type: 'time',
										content: {
											text: that.$base.__formatTime(chat.time)
										},
									})
								}
								that.timePointer = chat.time

								if (chat.type == 'img') {
									// chat.content = that.setPicSize(chat.content)
									that.chatImgList.push(chat.content.url)
								}
								if (chat.type == 'imgs') {
									if (idx < 0) idx = i

									for (var j in chat.content.list) {
										// chat.content.list[j] = that.setPicSize(chat.content.list[j])
										that.chatImgList.push(chat.content.list[j].url)
									}
								}
								chatList.push(chat)
							} catch (e) {
								console.log('getChatHistory error: ', e);
							}
						}

						// 咨询中插入
						if (that.orderStatus == 1) {
							chatList.splice(idx == 1 || this.cate == 'report' ? 3 : 2, 0, {
								cate: that.cate,
								orderno: that.orderno,
								fromType: 'system',
								type: 'tip',
								content: {
									text: "问诊已开始，本次问诊可持续" + this.patient_time_show
								},
							})
						}

						that.chatList = chatList

						if (that.orderStatus == 1) {
							that.$nextTick(function() {
								that.scrollToView = "chat-" + (that.chatList.length - 1)
							})
						}
					}
				})
			},
			consultationMsg() {
				this.timePointer = this.orderInfo.pay_time
				this.chatList = [];
				this.chatList.push({
					cate: this.cate,
					orderno: this.orderno,
					fromType: 'system',
					type: 'time',
					content: {
						// text: this.$base.__formatTime(this.orderInfo.pay_time)
						text: this.$base.__formatTime(this.orderInfo.createtime)
					},
				})

				if (this.cate != 'report') {
					this.chatList.push({
						cate: this.cate,
						orderno: this.orderno,
						fromType: 'user',
						from: this.isDoc ? this.ToUser : this.FromUser,
						to: this.isDoc ? this.FromUser : this.ToUser,
						type: 'textCard',
						content: {
							list: [{
									name: "咨询类型",
									value: this.orderInfo.consultation_consult_name
								},
								{
									name: "病情描述",
									value: this.orderInfo.content
								},
								// {name:"就诊情况", value:this.orderInfo.content},
							]
						},
						time: this.orderInfo.pay_time //createtime
					})

					if (this.orderInfo.images) {
						var images = this.orderInfo.images.toString().split(","),
							imgs = [],
							num = images.length
						for (var i in images) {
							if (images[i]) {
								imgs.push({
									url: images[i],
									w: 430 / (num - 1)
								})
								this.chatImgList.push(images[i])
							}
						}
						if (imgs.length > 0) {
							this.chatList.push({
								cate: this.cate,
								orderno: this.orderno,
								fromType: 'user',
								from: this.isDoc ? this.ToUser : this.FromUser,
								to: this.isDoc ? this.FromUser : this.ToUser,
								type: 'imgs',
								content: {
									list: imgs
								},
								time: this.orderInfo.pay_time //createtime
							})
						}
					}
				} else {
					this.chatList.push({
						cate: this.cate,
						orderno: this.orderno,
						fromType: 'user',
						from: this.isDoc ? this.ToUser : this.FromUser,
						to: this.isDoc ? this.FromUser : this.ToUser,
						type: 'text',
						content: {
							text: "您好，这是我的检测报告<br>麻烦帮忙看一下，谢谢！"
						},
						time: this.orderInfo.pay_time //createtime
					})
					this.chatList.push({
						cate: this.cate,
						orderno: this.orderno,
						fromType: 'user',
						from: this.isDoc ? this.ToUser : this.FromUser,
						to: this.isDoc ? this.FromUser : this.ToUser,
						type: 'file',
						content: {
							type: 'pdf',
							name: this.orderInfo.report_filename,
							url: this.orderInfo.report_url,
							time: this.$u.timeFormat(this.orderInfo.report_time)
						},
						time: this.orderInfo.pay_time //createtime
					})
				}

				if (this.orderStatus == 0) {
					this.chatList.push({
						cate: this.cate,
						orderno: this.orderno,
						fromType: 'system',
						type: 'waiting-for-treatment',
						content: {},
					})
				} else if (this.orderStatus == 1) {
					this.chatList.push({
						cate: this.cate,
						orderno: this.orderno,
						fromType: 'system',
						type: 'tip',
						content: {
							text: "问诊已开始，本次问诊可持续" + this.patient_time_show
						},
					})
				}

				// this.scrollToView = "chat-"+(this.chatList.length-3)
			},

			// 处理方法
			//替换表情符号为图片
			replaceEmoji(str) {
				// 正则表达式匹配内容
				var replacedStr = str.replace(/\[([^(\]|\[)]*)\]/g, (item, index) => {
					for (var i in this.emojiList) {
						var EM = this.emojiList[i]
						if (EM.alt == item) {
							return '<img class="lj-emoji" src="' + EM.url + '">'; //style="width:24px;height:24px;"
						}
					}
				});
				return '<div style="align-items: center;word-wrap:break-word;">' + replacedStr + '</div>';
			},
			// 计算年龄
			ages(str) {
				var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
				if (r == null) return 0;
				var d = new Date(r[1], r[3] - 1, r[4]);
				if (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4]) {
					var age = new Date().getFullYear() - r[1];
					return age > 0 ? age : 0
				}
				return 0;
			},
			formatSeconds(value, format, isFull) {
				var sec = parseInt(value); // 秒
				var minutes = 0; // 分
				var hour = 0; // 小时

				if (isFull) {
					if (sec > 60) {
						minutes = parseInt(sec / 60);
						sec = parseInt(sec % 60);
						if (minutes > 60) {
							hour = parseInt(minutes / 60);
							minutes = parseInt(minutes % 60);
						}
					}
				} else {
					hour = parseInt(sec / 3600)
					sec -= hour * 3600
					minutes = parseInt(sec / 60)
					sec -= minutes * 60
				}

				var result = ""
				for (var i in format) {
					if (i == 'h' && hour > 0) {
						result += (hour < 10 && isFull ? '0' + hour : hour) + format[i];
					}
					if (i == 'i' && (minutes > 0 || result)) {
						if (isFull || minutes > 0) result += (minutes < 10 && isFull ? '0' + minutes : minutes) + format[
							i];
					}
					if (i == 's' && (sec > 0 || result)) {
						if (isFull || sec > 0) result += (sec < 10 && isFull ? '0' + sec : sec) + format[i];
					}
				}

				return result;
			},
			//处理图片尺寸，如果不处理宽高，新进入页面加载图片时候会闪
			async setPicSize(content) {
				console.log('^^^^^ setPicSize', content)
				await uni.getImageInfo({
					src: content.url,
					success: function(image) {
						content.w = image.width
						content.h = image.height

						// 让图片最长边等于设置的最大长度，短边等比例缩小，图片控件真实改变，区别于aspectFit方式。
						let maxW = uni.upx2px(350); //350是定义消息图片最大宽度
						let maxH = uni.upx2px(350); //350是定义消息图片最大高度
						if (content.w > maxW || content.h > maxH) {
							let scale = content.w / content.h;
							content.w = scale > 1 ? maxW : maxH * scale;
							content.h = scale > 1 ? maxW / scale : maxH;
						}
						return content;
					},
					fail: function(msg) {
						return content
					}
				})
			},

			// 判断文件类型
			whatFileType(url) {
				let sr = url.lastIndexOf('.') //  最后一次出现的位置
				let fileType = url.substr((sr + 1)) // 截取url的类型
				return (fileType)
			},
			openFile(item) {
				console.log('openFile', item)
				var that = this
				if (item.type == 'pdf') {
					uni.showLoading({
						title: '加载中',
						mask: true
					})

					let fileType = this.whatFileType(item.url)
					console.log(wx.env.USER_DATA_PATH + "/" + (new Date().getTime()) + "." + fileType)
					uni.downloadFile({
						url: that.$base.img(item.url),
						// filePath: wx.env.USER_DATA_PATH + "/"+ (new Date().getTime()) + "."+fileType,
						success(res) {
							uni.hideLoading()
							var filePath = res.tempFilePath
							uni.showLoading({
								title: '正在打开',
								mask: true
							})

							uni.openDocument({
								filePath: filePath,
								// fileType: item.type,
								// showMenu: true,
								// flieType: fileType,
								success(res) {
									uni.hideLoading()

								},
								fail(err) {
									console.log('openDocument', err)
									uni.hideLoading()
									that.$u.toast('打开失败');
								}
							})
						},
						fail(err) {
							console.log('downloadFile', err)
							uni.hideLoading()
							that.$u.toast('加载失败');
						}
					})
				} else {
					that.$u.toast('开始下载【' + item.name + '】');
					uni.downloadFile({
						url: that.$base.img(item.url),
						success: (res) => {
							if (res.statusCode === 200) {
								console.log('下载成功');
								that.$u.toast('下载成功');
							}
						}
					})
				}
			},
		}
	}
</script>